package com.lizemin;

import com.lizemin.entity.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.sql.Date;

/**
 * @author: lizemin
 * @version: 1.0
 */
public class CRUDtest {
    Session session = null;
    Transaction tx = null;

    @Before
    public void init(){
        // A SessionFactory is set up once for an application!
        final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                .configure("hibernate.cfg.xml") // configures settings from hibernate.cfg.xml
                .build();
        SessionFactory sessionFactory = new MetadataSources(registry)
                .buildMetadata()
                .buildSessionFactory();
        //创建SQL session连接
        session = sessionFactory.openSession();
        //开启事务
        tx = session.beginTransaction();
    }

    @After
    public void closeConnection() {
        if (null != session && session.isOpen()){
            //关闭session
            session.close();
        }
    }

    /**
     * update方法根据id来定位要修改的数据，所以必须要指定id
     * update 2021_user set name=?, birth=? where id=?
     */
    @Test
    public void testUpdate(){
        //创建实例
        User user = new User();
        user.setId(1);
        user.setUsername("曹超2");
        user.setBirthday(new Date(System.currentTimeMillis()));
        //修改数据
        session.update(user);

        //提交事务
        tx.commit();
    }

    /**
     * saveOrUpdate:
     * 如果没有id,则发送insert插入数据
     * 如果有id,则发送update，修改数据
     */
    @Test
    public void testUpdate2(){
        //创建实例
        User user = new User();
//        user.setId(1);
        user.setUsername("曹超1000");
        user.setBirthday(new Date(System.currentTimeMillis()));
        //修改数据
        session.saveOrUpdate(user);

        //提交事务
        tx.commit();
    }

    /**
     * 删除操作:自动生成SQL语句
     * delete from 2021_user where id=?
     */
    @Test
    public void testDelete(){
        //创建实例
        User user = new User();
        user.setId(1);

        //删除数据
        session.delete(user);

        //提交事务
        tx.commit();
    }

    /**
     * 第二种查询
     *
     */
    @Test
    public void testSelect(){
        //创建实例
        User user = new User();
        user.setId(1);

        //查询数据
        User user2 = session.load(User.class, 94);
        System.out.println(user2);

        //select user0_.id as id1_2_0_, user0_.name as name2_2_0_, user0_.birth as birth3_2_0_ from 2021_user user0_ where user0_.id=?

        //提交事务
        tx.commit();
    }


    
}
